<script setup>
import { showToast, showNotify } from 'vant';

import { useRouter, useRoute } from 'vue-router'
const { proxy } = getCurrentInstance()
const router = useRouter()
const svg = ref('')
function login() {

  proxy.$api.login(loginForm).then(res => {
    // showToast({
    //   message: res.msg,
    //   position: 'top',
    // });
    showNotify({ type: 'success', message: res.msg });
    localStorage.setItem('token', res.data.token)
    let timer = setTimeout(() => {
      router.push('/index')
      clearTimeout(timer)
    }, 1000)
  }).catch(err => {
    if (err.status == -1) {
      getCaptcha()
    }

  })
}
function getCaptcha() {
  proxy.$api.captcha().then(res => {
    svg.value = res.img
  })
}

const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})
onMounted(() => {
  getCaptcha()

})
const value = ref(3);
</script>

<template>
  <div class="main">

    <van-form class="loginForm" :show-error-message="false">
      <van-cell-group inset>
        <van-field v-model="loginForm.username" name="用户名" label="用户名" placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="loginForm.password" type="password" name="密码" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
        <van-field v-model="loginForm.captcha" name="验证码" label="验证码" placeholder="验证码"
          :rules="[{ required: true, message: '请填写验证码' }]" @click-right-icon="getCaptcha">
          <template #right-icon>
            <div class="code" ref="code" v-html="svg">

            </div>
          </template>
        </van-field>
      </van-cell-group>

      <div style="margin: 16px;">
        <van-button round block type="primary" @click="login">
          登录
        </van-button>
      </div>
    </van-form>

  </div>
</template>
<style lang="less" scoped>
.loginForm {
  margin: 150px auto 0;
  display: inline-block;
  width: 100%;
}
</style>
